package ext.tianma.bom.service;

import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import ext.com.core.CoreUtil;
import ext.tianma.bom.util.GenericUtil;
import ext.tianma.bom.util.StringUtil;
import ext.tianma.part.PartWorkflowUtil;
import wt.fc.PersistenceHelper;
import wt.fc.QueryResult;
import wt.log4j.LogR;
import wt.part.WTPart;
import wt.part.WTPartUsageLink;
import wt.query.KeywordExpression;
import wt.query.QuerySpec;
import wt.query.SearchCondition;
import wt.util.WTException;
import wt.vc.OneOffVersionIdentifier;
import wt.vc.OneOffVersionInfo;
import wt.vc.VersionControlHelper;
import wt.vc.views.View;
import wt.vc.views.ViewHelper;

/**
 * 物料反查
 * 
 * @author gjw
 *
 */

@Controller
@RequestMapping({ "/MaterialReverse" })
public class MaterialReverseService {
	@Autowired
	HttpServletRequest request;

	private static final Logger log = LogR.getLogger(MaterialReverseService.class.getName());

	/**
	 * 根据物料编号返回相应结果
	 * 
	 * @param number
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping(value = "/tmMaterialReverse", method = { RequestMethod.POST, RequestMethod.GET })
	public void tmMaterialReverse(@RequestParam(value = "number", required = true) String number,
			@RequestParam(value = "view", required = false) String view,
			HttpServletResponse response) throws Exception {
		PrintWriter out = response.getWriter();
		String param222 = request.getParameter("number");
		log.info("======param =========" + param222);
		response.setContentType("application/json; charset=UTF-8");
		String result = "";
		/*
		 * result = firstValidate(); if (!isNullOrEmpty(result)) {
		 * out.print(result); return; }
		 */
		// 逻辑处理
		result = searhMaterialPart(number,view);
		out.print(result);
	}

	/**
	 * 通过物料编号查找其各视图使用关系 物料编码，物料视图，成品编码，成品版本，成品视图，半成品编码，半成品版本，半成品视图
	 * 
	 * { status:success/failed, datalist:[ {Number:XX01,PartView:"A10",
	 * FinishpartNumber:"xxx01",FinishpartVersion:"3.11",FinishpartView:"A10",
	 * SemiFinishedGoodNumber:"xxx01",SemiFinishedGoodVersion:"4.35",
	 * SemiFinishedGoodView:"A10"}, {} ] }
	 * 
	 * @param number
	 * @return
	 */
	public static String searhMaterialPart(String number,String view) {
		log.info("==================MaterialReverseService.searhMaterialPart================:" + number);
		JSONObject obj = new JSONObject();
		JSONArray array = new JSONArray();
		// 获取物料的全视图集合
		List<WTPart> list = new ArrayList<WTPart>();
		//视图
		List<String> viewlist = new ArrayList<String>();
		WTPart basicpart = null;
		try {
			 basicpart =  CoreUtil.getWTPartByNumberAndView(number, "Design");
		} catch (WTException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		if(StringUtil.isNullOrEmpty(view)){
			//WTPart part;
				// 获取design试图
				/*part = CoreUtil.getWTPartByNumberAndView(number, "Design");
				if(part!=null){
					list = PartWorkflowUtil.getAllPartViews(part);// 获取所有视图除Design
					list.add(part);// 增加到list中
				}*/
				list = getAllLatestVersionPart(number);
			
			
		}else{
			String[] views = view.split(",");
			try {
				for(String viewA:views){
					WTPart part = getPart(number, "", viewA);
					if(part != null){
						list.add(part);
					}
				}
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
		}

		// 存放物料对应的父层 key - value集合 或半成品与成品对应的key - value集合 ,用于展示
		Map<WTPart, ArrayList<WTPart>> firstLevolmap = new HashMap<WTPart, ArrayList<WTPart>>();

		// 父层关系集合
		List<WTPart> parentlist = new ArrayList<WTPart>();
		
		for (WTPart part1 : list) {
			
			firstLevolmap = getParentParts3(part1, parentlist, firstLevolmap,list);
		}
		/*for(WTPart part1 : list){
			viewlist.add(part1.getViewName());
		}
		if(basicpart!=null){
			parentlist = getParentParts2(basicpart, parentlist, firstLevolmap,viewlist);
		}*/
		
		log.info("=============parentlist1111:" + parentlist.size());
		log.info("=============parentlist1111:" + parentlist.toString());
		log.info("=======firstLevolmap:" + firstLevolmap.toString());
		log.info("=======list:" + list.size());
		
		log.info("=======list:" + list.toString());
		try {
			for (WTPart part1 : list) {
				log.info("=========part1:"+part1.getNumber()+"===view:"+part1.getViewName());
				// 取物料的半成品或成品集合
				ArrayList<WTPart> parentslist = firstLevolmap.get(part1);
				List<String> list222 = new ArrayList<String>(); 
				log.info("=======part1:" + part1.getNumber() + "==" + part1.getViewName() + "====version:"
						+ VersionControlHelper.getIterationDisplayIdentifier(part1).toString());
				// log.info("====searhMaterialPart
				// parentslist:"+parentslist.toString());
				if (parentslist != null) {
					for (WTPart showpart : parentslist) {
						String softtype = GenericUtil.getTypeId(showpart);
						String state = showpart.getState().getState().getDisplay(Locale.CHINA);
						if("废弃".equals(state)){
							continue;
						}
						log.info("====searhMaterialPart  softtype 1111:" + softtype);
						// 如果是成品 直接写值
						if (softtype.indexOf("cn.tianma.FinishedGood") != -1) {
							JSONObject object = new JSONObject();
							object.put("Number", part1.getNumber());
							object.put("PartView", part1.getViewName());
							object.put("State", part1.getState().getState().getDisplay(Locale.CHINA));
							// 成品属性
							object.put("FinishpartNumber", showpart.getNumber());
							object.put("FinishpartVersion",
									VersionControlHelper.getIterationDisplayIdentifier(showpart).toString());
							object.put("FinishpartView", showpart.getViewName());
							object.put("StateA", showpart.getState().getState().getDisplay(Locale.CHINA));

							// 半成品属性
							object.put("SemiFinishedGoodNumber", "");
							object.put("SemiFinishedGoodVersion", "");
							object.put("SemiFinishedGoodView", "");
							object.put("StateB", "");
							array.put(object);
							log.info("====searhMaterialPart  obj 111:" + object.toString());
						} else {
							log.info("====searhMaterialPart  softtype 2222:" + softtype);
							// 半成品 查找是否存在对应的成品
							ArrayList<WTPart> finishedlist = firstLevolmap.get(showpart);
							
							if (finishedlist != null && finishedlist.size() != 0) {
								//是否存在成品
								boolean flag = false;
								//是否已添加
								boolean addflag = false;
								for(WTPart halfpart : finishedlist){
									String halfsofttype = GenericUtil.getTypeId(halfpart);
									if (halfsofttype.indexOf("cn.tianma.FinishedGood") != -1) {
										flag = true;
										break;
									}
								}
								for (WTPart halfpart : finishedlist) {
									
									String halfsofttype = GenericUtil.getTypeId(halfpart);
									String halfstate = halfpart.getState().getState().getDisplay(Locale.CHINA);
									if("废弃".equals(halfstate)){
										continue;
									}
									JSONObject object = new JSONObject();
									object.put("Number", part1.getNumber());
									object.put("PartView", part1.getViewName());
									object.put("State", part1.getState().getState().getDisplay(Locale.CHINA));
									log.info("===halfpart number:"+halfpart.getNumber()+"--view:"+halfpart.getViewName()+"--type:"+halfsofttype);
									// 半成品存在相应的成品时
									if (halfsofttype.indexOf("cn.tianma.FinishedGood") != -1) {
										log.info("==========2222222222222222===="+halfpart.getNumber()+"--"+halfpart.getViewName()+"==="+parentslist.contains(halfpart));
										if(!parentslist.contains(halfpart)){
											// 成品属性
											object.put("FinishpartNumber", halfpart.getNumber());
											object.put("FinishpartVersion", VersionControlHelper
													.getIterationDisplayIdentifier(halfpart).toString());
											object.put("FinishpartView", halfpart.getViewName());
											object.put("StateA", halfpart.getState().getState().getDisplay(Locale.CHINA));
											// 半成品属性
											object.put("SemiFinishedGoodNumber", showpart.getNumber());
											object.put("SemiFinishedGoodVersion", VersionControlHelper
													.getIterationDisplayIdentifier(showpart).toString());
											object.put("SemiFinishedGoodView", showpart.getViewName());
											object.put("StateB", showpart.getState().getState().getDisplay(Locale.CHINA));
											array.put(object);
										}

									} else {
										// 成品属性
										if(!flag){
											object.put("FinishpartNumber", "");
											object.put("FinishpartVersion", "");
											object.put("FinishpartView", "");
											object.put("StateA", "");

											// 半成品属性
											object.put("SemiFinishedGoodNumber", showpart.getNumber());
											object.put("SemiFinishedGoodVersion", VersionControlHelper
													.getIterationDisplayIdentifier(showpart).toString());
											object.put("SemiFinishedGoodView", showpart.getViewName());
											object.put("StateB", showpart.getState().getState().getDisplay(Locale.CHINA));

											array.put(object);
											flag = true;
										}
										//继续往根节点取成品
										array = FinishedGoodArray(firstLevolmap,array,halfpart,part1);
									}

									log.info("====searhMaterialPart  obj 222:" + object.toString());
									//break;
								}
							} else if (finishedlist != null && finishedlist.size() == 0) {
								log.info("===showpart number:"+showpart.getNumber()+"--view:"+showpart.getViewName()+"--type:"+softtype);

								// 半成品未找到相应的成品
								JSONObject object = new JSONObject();
								object.put("Number", part1.getNumber());
								object.put("PartView", part1.getViewName());
								object.put("State", part1.getState().getState().getDisplay(Locale.CHINA));

								// 成品属性
								object.put("FinishpartNumber", "");
								object.put("FinishpartVersion", "");
								object.put("FinishpartView", "");
								object.put("StateA", "");

								// 半成品属性
								object.put("SemiFinishedGoodNumber", showpart.getNumber());
								object.put("SemiFinishedGoodVersion",
										VersionControlHelper.getIterationDisplayIdentifier(showpart).toString());
								object.put("SemiFinishedGoodView", showpart.getViewName());
								object.put("StateB", showpart.getState().getState().getDisplay(Locale.CHINA));

								
								array.put(object);

								log.info("====searhMaterialPart  obj 333:" + object.toString());
							}else if (finishedlist == null) {
								log.info("===showpart number:"+showpart.getNumber()+"--view:"+showpart.getViewName()+"--type:"+softtype);

								// 半成品未找到相应的成品
								JSONObject object = new JSONObject();
								object.put("Number", part1.getNumber());
								object.put("PartView", part1.getViewName());
								object.put("State", part1.getState().getState().getDisplay(Locale.CHINA));

								// 成品属性
								object.put("FinishpartNumber", "");
								object.put("FinishpartVersion", "");
								object.put("FinishpartView", "");
								object.put("StateA", "");

								// 半成品属性
								object.put("SemiFinishedGoodNumber", showpart.getNumber());
								object.put("SemiFinishedGoodVersion",
										VersionControlHelper.getIterationDisplayIdentifier(showpart).toString());
								object.put("SemiFinishedGoodView", showpart.getViewName());
								object.put("StateB", showpart.getState().getState().getDisplay(Locale.CHINA));

								
								array.put(object);

								log.info("====searhMaterialPart  obj 333:" + object.toString());
							}

						}
					}
				}
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			log.info("========Exception:" + e.getMessage());
		}
		try {
			obj.put("status", "success");
			obj.put("datalist", array);
			obj.put("length", array.length());

		} catch (JSONException e) {
			log.error(e.getMessage(), e);
		}
		log.info("====MaterialReverseService.searhMaterialPart:" + obj.toString());
		return obj.toString();
	}

	/**
	 * 根据部件编号获取所有最新小版本
	 * 
	 */
	public static List<WTPart> getAllLatestVersionPart(String number) {
		List<WTPart> list = new ArrayList<WTPart>();
		WTPart part = null;
		QuerySpec qs;
		try {
			qs = new QuerySpec(WTPart.class);
			SearchCondition sc = new SearchCondition(WTPart.class, WTPart.NUMBER, SearchCondition.EQUAL, number);
			qs.appendWhere(sc);
			qs.appendAnd();
			qs.appendWhere(new SearchCondition(new KeywordExpression("A0.latestiterationinfo"), SearchCondition.EQUAL,
					new KeywordExpression("1")));
			qs.appendOrderBy(WTPart.class, "thePersistInfo.createStamp", true);
			QueryResult qr2 = PersistenceHelper.manager.find(qs);
			while (qr2.hasMoreElements()) {
				part = (WTPart) qr2.nextElement();
				wt.vc.VersionIdentifier vi = wt.vc.VersionControlHelper.nextVersionId(part);
				String v = vi.getValue();
				wt.part.WTPart p = getPart(part.getNumber(), v, part.getView().getName());
				if (null != p) {
					continue;
				}
				String version = VersionControlHelper.getIterationDisplayIdentifier(part).toString();
				log.info("view:" + part.getViewName() + "===version:" + version + "<br>");
				if (!list.contains(part)) {
					list.add(part);
				}
			}
		} catch (Exception e) {

		}
		return list;

	}

	/**
	 * 获取关系中的部件
	 * 
	 * @param part
	 * @param list
	 * @return
	 */
	/*
	 * public static List<WTPart> getchildPart(WTPart part, List<WTPart> list,
	 * JSONArray array, WTPart initPart) { try { if (part != null) { QueryResult
	 * qs = WTPartHelper.service.getUsesWTPartMasters(part); while
	 * (qs.hasMoreElements()) { WTPartUsageLink link = (WTPartUsageLink)
	 * qs.nextElement(); WTPartMaster master = (WTPartMaster)
	 * link.getRoleBObject(); WTPart childpart =
	 * PartUtil.getLatestPartByPartMaster(master); if
	 * (!list.contains(childpart)) { list.add(childpart); }
	 * getchildPart(childpart, list, array, initPart); } } } catch (WTException
	 * e) { e.printStackTrace(); } return list; }
	 */

	/**
	 * 空或者NULL值时返回true
	 * 
	 * @param str
	 * @return
	 */
	public static boolean isNullOrEmpty(String str) {
		return (str == null || "".equals(str) || str.equals("null") || str.equals("NULL"));
	}

	/**
	 * 根据编号 版本 视图返回部件
	 * 
	 * @param num
	 * @param ver
	 * @param viewName
	 * @return
	 * @throws Exception
	 */
	public static WTPart getPart(String num, String ver, String viewName) throws Exception {
		if (viewName.equals(""))
			viewName = "Design";
		if (num == null || num.equals("") || num.trim().equals(""))
			return null;
		View view = ViewHelper.service.getView(viewName);
		WTPart part = null;
		QuerySpec qs = new QuerySpec(WTPart.class);
		SearchCondition sc = new SearchCondition(WTPart.class, WTPart.NUMBER, SearchCondition.EQUAL, num);
		qs.appendWhere(sc);
		sc = new SearchCondition(WTPart.class, "view.key.id", SearchCondition.EQUAL,
				view.getPersistInfo().getObjectIdentifier().getId());
		qs.appendAnd();
		qs.appendWhere(sc);
		if (!ver.equals("")) {
			qs.appendAnd();
			qs.appendWhere(new SearchCondition(new KeywordExpression("A0.versionida2versioninfo"),
					SearchCondition.EQUAL, new KeywordExpression("'" + ver + "'")));
		}
		qs.appendAnd();
		qs.appendWhere(new SearchCondition(new KeywordExpression("A0.latestiterationinfo"), SearchCondition.EQUAL,
				new KeywordExpression("1")));

		qs.appendOrderBy(WTPart.class, "thePersistInfo.createStamp", true);
		QueryResult qr = PersistenceHelper.manager.find(qs);
		while (qr.hasMoreElements()) {
			part = (WTPart) qr.nextElement();
			OneOffVersionInfo one = part.getOneOffVersionInfo();
			OneOffVersionIdentifier id = one.getIdentifier();
			String valueOneOff = id.getValue();
			if (valueOneOff == null)
				return part;
		}
		return part;
	}

	/**
	 * 取父关系部件集合
	 * 
	 * @param part
	 * @param list
	 * @return
	 */
	public static Map<WTPart, ArrayList<WTPart>> getParentParts(WTPart part, List<WTPart> list,
			Map<WTPart, ArrayList<WTPart>> firstLevolmap,List<WTPart> partlist) {
		try {
			// 方法一
			log.info("================getParentParts start========== ");
			log.info("=====getParentParts part:"+part.getNumber()+"---view:"+part.getViewName());
			QueryResult partsqr  = PersistenceHelper.manager.navigate(part.getMaster(), WTPartUsageLink.ALL_ROLES,
					WTPartUsageLink.class,true);
			log.info("=====getParentParts partsqr:"+partsqr.size());
			//QueryResult result = PersistenceHelper.manager.navigate(part.getMaster(), WTPartUsageLink.ALL_ROLES,
			//		WTPartUsageLink.class);
			//log.info("=====Size 1:"+partsqr.size());
			//log.info("=====Size 2:"+result.size());
			//QueryResult result=PersistenceHelper.manager.navigate(part,WTPartUsageLink.USES_ROLE,WTPartUsageLink.class,true);

			// 方法二
			// List<WTPart> parentslist = BOMHelp.getWTPartUsageLinkNew(part);
			// 取父关系
			while (partsqr.hasMoreElements()) {
				// for(WTPart partA : parentslist){
				WTPart partA = (WTPart) partsqr.nextElement();
				log.info("=====getParentParts partsqr partA:"+partA.getNumber()+"---view:"+partA.getViewName()+ "====version:"
						+ VersionControlHelper.getIterationDisplayIdentifier(partA).toString());

				List<WTPart> latestlist = getAllLatestVersionPart(partA.getNumber());
				
				// 去掉这层循环取得是历史版本
				if (latestlist.contains(partA) && !list.contains(partA) && partA.isLatestIteration()) {
					if (!list.contains(partA) && partA.isLatestIteration()
							&& partA.getViewName().equals(part.getViewName())) {
						String softType = GenericUtil.getTypeId(partA);
						if (softType.indexOf("cn.tianma.FinishedGood") != -1
								|| softType.indexOf("cn.tianma.SemiFinishedGood") != -1) {
							log.info("=correct======partA:" + partA.getNumber() + "==" + partA.getViewName()
									+ "====version:"
									+ VersionControlHelper.getIterationDisplayIdentifier(partA).toString()+"===number:"+part.getNumber()+"==view:"+part.getViewName());
							// 已包含 成品或半成品
							if (firstLevolmap.containsKey(part)) {
								log.info("containsKey:" + partA.getNumber());
								ArrayList<WTPart> parentparts = firstLevolmap.get(part);
								parentparts.add(partA);
								firstLevolmap.put(part, parentparts);
							} else {
								log.info("not containsKey:" + partA.getNumber());
								// 不包含 成品或半成品
								ArrayList<WTPart> childparts = new ArrayList<WTPart>();
								childparts.add(partA);
								firstLevolmap.put(part, childparts);
							}
							
							list.add(partA);

							// 递归查询
							firstLevolmap = getParentParts(partA, list, firstLevolmap,partlist);
						}
						/*list.add(partA);

						// 递归查询
						getParentParts(partA, list, firstLevolmap,parentlist2);*/
					}
				}
			}
		} catch (Exception e) {
			log.error(e.getMessage(), e);
		}

		return firstLevolmap;
	}
	/**
	 * 通过物料A查找非直接关系的成品D
	 * 如：A-->B-->C-->D
	 * 通过A找到半成品B 再间接找到成品D  B、D不存在直接关系
	 * @param firstLevolmap 
	 * @param array  显示的内容
	 * @param part   
	 * @param basicpart
	 * @return
	 * @throws Exception
	 */
	public static JSONArray FinishedGoodArray(Map<WTPart, ArrayList<WTPart>> firstLevolmap,
			JSONArray array,WTPart part,WTPart basicpart) throws Exception{
		if(firstLevolmap.containsKey(part)){
			ArrayList<WTPart> finishedlist = firstLevolmap.get(part);
			for (WTPart halfpart : finishedlist) {
				//类型
				String halfsofttype = GenericUtil.getTypeId(halfpart);
				String halfstate = halfpart.getState().getState().getDisplay(Locale.CHINA);
				if("废弃".equals(halfstate)){
					continue;
				}
				JSONObject object = new JSONObject();
				object.put("Number", basicpart.getNumber());
				object.put("PartView", basicpart.getViewName());
				object.put("State", basicpart.getState().getState().getDisplay(Locale.CHINA));

				// 半成品存在相应的成品时
				// 成品属性
				if (halfsofttype.indexOf("cn.tianma.FinishedGood") != -1) {
					log.info("==========333333333333333333===="+halfpart.getNumber()+"--"+halfpart.getViewName()+"==="+finishedlist.contains(halfpart));
					object.put("FinishpartNumber", halfpart.getNumber());
					object.put("FinishpartVersion", VersionControlHelper
							.getIterationDisplayIdentifier(halfpart).toString());
					object.put("FinishpartView", halfpart.getViewName());
					object.put("StateA", halfpart.getState().getState().getDisplay(Locale.CHINA));

					// 半成品属性
					object.put("SemiFinishedGoodNumber", "");
					object.put("SemiFinishedGoodVersion", "");
					object.put("SemiFinishedGoodView", "");
					object.put("StateB", "");

					array.put(object);
					//return array;
				}else{
					array = FinishedGoodArray(firstLevolmap,array,halfpart,basicpart);
				} 
			}
		}
		
		return array;
	}
	/**
	 * 取父关系部件集合
	 * 
	 * @param part
	 * @param list
	 * @return
	 */
	public static List<WTPart> getParentParts2(WTPart part, List<WTPart> list,
			Map<WTPart, ArrayList<WTPart>> firstLevolmap,List<String> viewlist) {
		QueryResult partsqr;
		try {
			// 方法一
			partsqr = PersistenceHelper.manager.navigate(part.getMaster(), WTPartUsageLink.ALL_ROLES,
					WTPartUsageLink.class,true);
			log.info("=====getParentParts partsqr:"+partsqr.size());

			// 方法二
			// List<WTPart> parentslist = BOMHelp.getWTPartUsageLinkNew(part);
			// 取父关系
			while (partsqr.hasMoreElements()) {
				// for(WTPart partA : parentslist){
				WTPart partA = (WTPart) partsqr.nextElement();
				log.info("=====getParentParts partsqr partA:"+partA.getNumber()+"---view:"+partA.getViewName()+ "====version:"
						+ VersionControlHelper.getIterationDisplayIdentifier(partA).toString());

				List<WTPart> latestlist = getAllLatestVersionPart(partA.getNumber());
				
				// 去掉这层循环取得是历史版本
				if (latestlist.contains(partA) && !list.contains(partA) && partA.isLatestIteration()) {
					/*if (!list.contains(partA) && partA.isLatestIteration()
							&& partA.getViewName().equals(part.getViewName())) {*/
					if (!list.contains(partA) && partA.isLatestIteration()
							&& viewlist.contains(partA.getViewName())) {
						String softType = GenericUtil.getTypeId(partA);
						if (softType.indexOf("cn.tianma.FinishedGood") != -1
								|| softType.indexOf("cn.tianma.SemiFinishedGood") != -1) {
							log.info("=correct======partA:" + partA.getNumber() + "==" + partA.getViewName()
									+ "====version:"
									+ VersionControlHelper.getIterationDisplayIdentifier(partA).toString());
							// 已包含 成品或半成品
							part = GenericUtil.getPart(part.getNumber(), "", partA.getViewName());
							if(part!=null){
								if (firstLevolmap.containsKey(part)) {
									log.info("containsKey:" + partA.getNumber());
									ArrayList<WTPart> parentparts = firstLevolmap.get(part);
									parentparts.add(partA);
									firstLevolmap.put(part, parentparts);
								} else {
									log.info("not containsKey:" + partA.getNumber());
									// 不包含 成品或半成品
									ArrayList<WTPart> childparts = new ArrayList<WTPart>();
									childparts.add(partA);
									firstLevolmap.put(part, childparts);
								}
								
								list.add(partA);

								// 递归查询
								getParentParts2(partA, list, firstLevolmap,viewlist);
							}
						}
						/*list.add(partA);

						// 递归查询
						getParentParts(partA, list, firstLevolmap,parentlist2);*/
					}
				}
			}
		} catch (Exception e) {
			log.error(e.getMessage(), e);
		}

		return list;
	}
	/**
	 * 取父关系部件集合
	 * 
	 * @param part
	 * @param list
	 * @return
	 */
	public static Map<WTPart, ArrayList<WTPart>> getParentParts3(WTPart part, List<WTPart> list,
			Map<WTPart, ArrayList<WTPart>> firstLevolmap,List<WTPart> partlist) {
		List<WTPart> partlist222 = new ArrayList<WTPart>();
		try {
			// 方法一
			log.info("================getParentParts start========== ");
			log.info("=====getParentParts part:"+part.getNumber()+"---view:"+part.getViewName());
			QueryResult partsqr  = PersistenceHelper.manager.navigate(part.getMaster(), WTPartUsageLink.ALL_ROLES,
					WTPartUsageLink.class,true);
			log.info("=====getParentParts partsqr:"+partsqr.size());
			//QueryResult result = PersistenceHelper.manager.navigate(part.getMaster(), WTPartUsageLink.ALL_ROLES,
			//		WTPartUsageLink.class);
			//log.info("=====Size 1:"+partsqr.size());
			//log.info("=====Size 2:"+result.size());
			//QueryResult result=PersistenceHelper.manager.navigate(part,WTPartUsageLink.USES_ROLE,WTPartUsageLink.class,true);

			// 方法二
			// List<WTPart> parentslist = BOMHelp.getWTPartUsageLinkNew(part);
			// 取父关系
			while (partsqr.hasMoreElements()) {
				// for(WTPart partA : parentslist){
				WTPart partA = (WTPart) partsqr.nextElement();
				log.info("=====getParentParts partsqr partA:"+partA.getNumber()+"---view:"+partA.getViewName()+ "====version:"
						+ VersionControlHelper.getIterationDisplayIdentifier(partA).toString());

				List<WTPart> latestlist = getAllLatestVersionPart(partA.getNumber());
				
				// 去掉这层循环取得是历史版本
				if (latestlist.contains(partA) && !list.contains(partA) && partA.isLatestIteration()) {
					if (!list.contains(partA) && partA.isLatestIteration()
							&& partA.getViewName().equals(part.getViewName())) {
						String softType = GenericUtil.getTypeId(partA);
						if (softType.indexOf("cn.tianma.FinishedGood") != -1
								|| softType.indexOf("cn.tianma.SemiFinishedGood") != -1) {
							log.info("=correct======partA:" + partA.getNumber() + "==" + partA.getViewName()
									+ "====version:"
									+ VersionControlHelper.getIterationDisplayIdentifier(partA).toString()+"===number:"+part.getNumber()+"==view:"+part.getViewName());
							// 已包含 成品或半成品
							if (firstLevolmap.containsKey(part)) {
								log.info("containsKey:" + partA.getNumber());
								ArrayList<WTPart> parentparts = firstLevolmap.get(part);
								parentparts.add(partA);
								firstLevolmap.put(part, parentparts);
							} else {
								log.info("not containsKey:" + partA.getNumber());
								// 不包含 成品或半成品
								ArrayList<WTPart> childparts = new ArrayList<WTPart>();
								childparts.add(partA);
								firstLevolmap.put(part, childparts);
							}
							partlist222.add(partA);
							//list.add(partA);

							// 递归查询
							//firstLevolmap = getParentParts(partA, list, firstLevolmap,partlist);
						}
						/*list.add(partA);

						// 递归查询
						getParentParts(partA, list, firstLevolmap,parentlist2);*/
					}
				}
			}
			for(WTPart part222 : partlist222){
				firstLevolmap = getParentParts3(part222, list, firstLevolmap,partlist);
			}
		} catch (Exception e) {
			log.error(e.getMessage(), e);
		}

		return firstLevolmap;
	}
}
